package com.suxin.rpc;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * @author Tang
 * @classname NettyClient
 * @description [ TODO ]
 * @date 2021/1/17 19:28
 */
public class NettyClient {

    private static NettyClientHandler clientHandler;

    private static ExecutorService executor = Executors.newFixedThreadPool(10);

    private static String providerName = "HelloService#hello#";

    public static Object getBean(Class<?> clazz) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{clazz}, (proxy, method, args) -> {

                    if (clientHandler == null) {
                        init();
                    }

                    clientHandler.setParams(providerName + args[0]);

                    FutureTask<Object> futureTask = new FutureTask<>(clientHandler);
                    executor.execute(futureTask);

                    return futureTask.get();
                });
    }

    public static void main(String[] args) {
        HelloService bean = (HelloService) getBean(HelloService.class);
        String result = bean.hello("hello world!");
        System.out.println(result);
    }

    public static void init() {
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        clientHandler = new NettyClientHandler();
        try {
            bootstrap.group(workGroup)
                    .option(ChannelOption.TCP_NODELAY,true)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(clientHandler);
                        }
                    });
            System.out.println("client ready...");
            bootstrap.connect("127.0.0.1", 7000).sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workGroup.shutdownGracefully();
        }
    }

}